import axios from 'axios'

const request = axios.create({
  baseURL: import.meta.env.DEV ? '/api' : 'http://localhost:8080',
  timeout: 10000
})

request.interceptors.request.use(config => {
  if (config.method === 'post' && !config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }
  return config
})

request.interceptors.response.use(
  res => res.data,
  err => {
    console.error(err)
    return Promise.reject(err)
  }
)

const toParams = obj => {
  const p = new URLSearchParams()
  Object.entries(obj).forEach(([k, v]) => {
    if (v !== '' && v != null) p.append(k, v)
  })
  return p
}

export const register = data => request.post('/user/register.do', toParams(data))

export const login = data => request.post('/user/login.do', toParams(data))

export const logout = () => request.post('/user/logout.do')

export const checkLogin = () => request.get('/user/checkLogin.do')

export const getProfile = params => request.get('/user/profile.do', { params })

export const updateProfile = data => request.post('/user/updateProfile.do', toParams(data))

export const changePassword = data => request.post('/user/changePassword.do', toParams(data))

export const getUserList = params => request.get('/user/pageList.do', { params: toParams(params) })

export const updateUser = data => request.post('/user/update.do', toParams(data))

export const deleteUser = data => request.post('/user/delete.do', toParams(data))

export const generateAvatar = params => request.get('/user/generateAvatar.do', { params })
